package br.unicamp.mc715.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import br.unicamp.mc715.common.MC715SerializationException;

/**
 * This class holds utility functions related to marshalling and unmarshalling
 * of serializable objects. <p>
 *
 */

public class Marshall {

    /**
     * Marshalls a serializable object into a byte array. <p>
     * 
     * @param o the object to the marshalled.
     * @return a newly allocated byte array containing the marshalled object. 
     * @throws MC715SerializationException if a serialization error occurs.
     */
    public static byte[] marshall(Serializable o) throws MC715SerializationException {
        ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
        try {
            ObjectOutputStream out = new ObjectOutputStream(outBuffer);
            out.writeObject(o);
        } catch (IOException e) {
            throw new MC715SerializationException(e);
        }
        return outBuffer.toByteArray();
    }

    /**
     * Unmarshalls a serializable object from a byte array. <p>
     * 
     * @param buffer the byte array.
     * @return the unmarshalled object. 
     * @throws MC715SerializationException if a serialization error occurs.
     */
    public static Serializable unmarshall(byte[] buffer)
            throws MC715SerializationException {
        try {
            ObjectInputStream in = new ObjectInputStream(
                    new ByteArrayInputStream(buffer, 0, buffer.length));
            return (Serializable) in.readObject();
        } catch (ClassNotFoundException e) {
            throw new MC715SerializationException(e);
        } catch (IOException e) {
            throw new MC715SerializationException(e);
        }
    }

}
